<template>
  <div class="flex flex-col gap-3 flex-1">
    <!-- 顶部统计卡片 -->
    <div class="grid grid-cols-4 gap-3 bg-white p-3 rounded-lg">
      <el-card v-for="stat in statistics" :key="stat.label" shadow="hover">
        <div class="flex items-center justify-between">
          <div class="flex flex-col">
            <span class="text-gray-500 text-sm">{{ stat.label }}</span>
            <span class="text-2xl font-bold mt-2" :class="stat.color">{{ stat.value }}</span>
          </div>
          <el-icon :size="40" :class="stat.iconColor">
            <component :is="stat.icon" />
          </el-icon>
        </div>
      </el-card>
    </div>

    <!-- 主要内容区域 -->
    <el-tabs v-model="activeTab" class="flex-1 bg-white p-3 rounded-lg mb-0">
      <!-- 会员列表 -->
      <el-tab-pane label="会员列表" name="members">
        <div class="bg-white p-3 rounded-lg">
          <!-- 搜索栏 -->
          <div class="flex gap-3 mb-3">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索会员姓名/手机号"
              class="w-60"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="searchForm.level" placeholder="会员等级" class="w-40">
              <el-option
                v-for="level in memberLevels"
                :key="level.value"
                :label="level.label"
                :value="level.value"
              />
            </el-select>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>

          <!-- 会员表格 -->
          <el-table :data="members" border stripe>
            <el-table-column type="expand">
              <template #default="props">
                <div class="p-3">
                  <el-descriptions :column="3" border>
                    <el-descriptions-item label="累计消费">
                      ¥{{ props.row.totalSpent }}
                    </el-descriptions-item>
                    <el-descriptions-item label="可用积分">
                      {{ props.row.points }}
                    </el-descriptions-item>
                    <el-descriptions-item label="注册时间">
                      {{ props.row.registerTime }}
                    </el-descriptions-item>
                    <el-descriptions-item label="最近就诊">
                      {{ props.row.lastVisit }}
                    </el-descriptions-item>
                    <el-descriptions-item label="就诊次数">
                      {{ props.row.visitCount }}
                    </el-descriptions-item>
                    <el-descriptions-item label="推荐人数">
                      {{ props.row.referralCount }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="会员姓名" />
            <el-table-column prop="phone" label="手机号" />
            <el-table-column prop="level" label="会员等级">
              <template #default="{ row }">
                <el-tag :type="getMemberLevelType(row.level)">
                  {{ getMemberLevelLabel(row.level) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="points" label="积分" />
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                  {{ row.status === 'active' ? '正常' : '已冻结' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" >
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEditMember(row)">
                  编辑
                </el-button>
                <el-button type="success" link @click="handleViewPoints(row)">
                  积分明细
                </el-button>
                <el-button 
                  :type="row.status === 'active' ? 'danger' : 'success'"
                  link 
                  @click="handleToggleMemberStatus(row)"
                >
                  {{ row.status === 'active' ? '冻结' : '解冻' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 等级特权 -->
      <el-tab-pane label="等级特权" name="levels">
        <div class="bg-white rounded-lg">
          <div class="flex justify-between mb-3">
            <h3 class="text-lg font-bold mb-0 mt-0">等级设置</h3>
            <el-button type="primary" @click="handleCreateLevel">新增等级</el-button>
          </div>

          <el-table :data="levelSettings" border stripe>
            <el-table-column prop="name" label="等级名称" />
            <el-table-column prop="condition" label="升级条件">
              <template #default="{ row }">
                <div class="flex flex-col gap-1">
                  <el-tag size="small" effect="plain">
                    累计消费：¥{{ row.spendRequirement }}
                  </el-tag>
                  <el-tag size="small" effect="plain">
                    积分要求：{{ row.pointRequirement }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="benefits" label="等级特权">
              <template #default="{ row }">
                <div class="flex flex-col gap-1">
                  <el-tag 
                    v-for="(benefit, index) in row.benefits" 
                    :key="index"
                    size="small"
                    effect="plain"
                  >
                    {{ benefit }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="discount" label="折扣">
              <template #default="{ row }">
                {{ row.discount }}折
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEditLevel(row)">
                  编辑
                </el-button>
                <el-button type="danger" link @click="handleDeleteLevel(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 积分规则 -->
      <el-tab-pane label="积分规则" name="points">
        <div class="bg-white rounded-lg">
          <div class="flex justify-between mb-3">
            <h3 class="text-lg font-bold mb-0 mt-0">积分规则设置</h3>
            <el-button type="primary" @click="handleCreatePointRule">新增规则</el-button>
          </div>

          <el-table :data="pointRules" border stripe>
            <el-table-column prop="name" label="规则名称" />
            <el-table-column prop="type" label="类型">
              <template #default="{ row }">
                <el-tag :type="getPointRuleType(row.type)">
                  {{ getPointRuleLabel(row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="points" label="积分" />
            <el-table-column prop="description" label="说明" />
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-switch
                  v-model="row.status"
                  :active-value="'active'"
                  :inactive-value="'inactive'"
                  @change="handleTogglePointRule(row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEditPointRule(row)">
                  编辑
                </el-button>
                <el-button type="danger" link @click="handleDeletePointRule(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 会员编辑对话框 -->
    <Drawer
      v-model="showMemberDialog"
      :title="editingMember.id ? '编辑会员' : '新增会员'"
      size="500px"
      @confirm="handleConfirmMember"
    >
      <el-form :model="editingMember" label-width="100px">
        <el-form-item label="会员姓名">
          <el-input v-model="editingMember.name" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editingMember.phone" />
        </el-form-item>
        <el-form-item label="会员等级">
          <el-select v-model="editingMember.level" class="w-full">
            <el-option
              v-for="level in memberLevels"
              :key="level.value"
              :label="level.label"
              :value="level.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="积分">
          <el-input-number v-model="editingMember.points" :min="0" />
        </el-form-item>
      </el-form>
    </Drawer>

    <!-- 等级编辑对话框 -->
    <Drawer
      v-model="showLevelDialog"
      :title="editingLevel.id ? '编辑等级' : '新增等级'"
      size="500px"
      @confirm="handleConfirmLevel"
    >
      <el-form :model="editingLevel" label-width="100px">
        <el-form-item label="等级名称">
          <el-input v-model="editingLevel.name" />
        </el-form-item>
        <el-form-item label="消费要求">
          <el-input-number v-model="editingLevel.spendRequirement" :min="0" />
        </el-form-item>
        <el-form-item label="积分要求">
          <el-input-number v-model="editingLevel.pointRequirement" :min="0" />
        </el-form-item>
        <el-form-item label="折扣">
          <el-input-number v-model="editingLevel.discount" :min="1" :max="10" :step="0.1" />
        </el-form-item>
        <el-form-item label="等级特权">
          <div v-for="(benefit, index) in editingLevel.benefits" :key="index" class="mb-2">
            <div class="flex gap-2">
              <el-input v-model="editingLevel.benefits[index]" />
              <el-button type="danger" circle @click="removeBenefit(index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
          <el-button type="primary" link @click="addBenefit">
            <el-icon><Plus /></el-icon>
            添加特权
          </el-button>
        </el-form-item>
      </el-form>
    </Drawer>

    <!-- 积分规则编辑对话框 -->
    <Drawer
      v-model="showPointRuleDialog"
      :title="editingPointRule.id ? '编辑规则' : '新增规则'"
      size="500px"
      @confirm="handleConfirmPointRule"
    >
      <el-form :model="editingPointRule" label-width="100px">
        <el-form-item label="规则名称">
          <el-input v-model="editingPointRule.name" />
        </el-form-item>
        <el-form-item label="规则类型">
          <el-select v-model="editingPointRule.type" class="w-full">
            <el-option label="消费获得" value="spend" />
            <el-option label="推荐奖励" value="referral" />
            <el-option label="活动奖励" value="activity" />
          </el-select>
        </el-form-item>
        <el-form-item label="积分">
          <el-input-number v-model="editingPointRule.points" :min="0" />
        </el-form-item>
        <el-form-item label="规则说明">
          <el-input
            v-model="editingPointRule.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
    </Drawer>

    <!-- 积分明细对话框 -->
    <Drawer
      v-model="showPointsDetailDialog"
      title="积分明细"
      size="800px"
      @confirm="handleConfirmPointsDetail"
    >
      <div class="flex flex-col gap-4">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="会员姓名">
            {{ selectedMember?.name }}
          </el-descriptions-item>
          <el-descriptions-item label="当前积分">
            {{ selectedMember?.points }}
          </el-descriptions-item>
          <el-descriptions-item label="累计获得">
            {{ selectedMember?.totalPoints }}
          </el-descriptions-item>
        </el-descriptions>

        <el-table :data="pointsHistory" border stripe>
          <el-table-column prop="time" label="时间" width="160" />
          <el-table-column prop="type" label="类型">
            <template #default="{ row }">
              <el-tag :type="getPointHistoryType(row.type)">
                {{ getPointHistoryLabel(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="points" label="积分变动">
            <template #default="{ row }">
              <span :class="row.points > 0 ? 'text-green-500' : 'text-red-500'">
                {{ row.points > 0 ? '+' : '' }}{{ row.points }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="说明" />
          <el-table-column prop="balance" label="积分余额" />
        </el-table>
      </div>
    </Drawer>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus, Search, Star, Medal, Money, Present } from '@element-plus/icons-vue'
import Drawer from '@/components/common/Drawer.vue'

// 页面状态
const activeTab = ref('members')
const searchForm = ref({
  keyword: '',
  level: ''
})

// 统计数据
const statistics = ref([
  {
    label: '会员总数',
    value: '1,256',
    icon: 'Medal',
    color: 'text-blue-500',
    iconColor: 'text-blue-200'
  },
  {
    label: '本月新增',
    value: '128',
    icon: 'Plus',
    color: 'text-green-500',
    iconColor: 'text-green-200'
  },
  {
    label: '会员消费',
    value: '￥125,600',
    icon: 'Money',
    color: 'text-orange-500',
    iconColor: 'text-orange-200'
  },
  {
    label: '积分发放',
    value: '25,600',
    icon: 'Present',
    color: 'text-purple-500',
    iconColor: 'text-purple-200'
  }
])

// 会员等级选项
const memberLevels = [
  { label: '普通会员', value: 'normal' },
  { label: '银卡会员', value: 'silver' },
  { label: '金卡会员', value: 'gold' },
  { label: '钻石会员', value: 'diamond' }
]

// 会员数据
const members = ref([
  {
    id: '1',
    name: '张三',
    phone: '13800138000',
    level: 'gold',
    points: 1200,
    status: 'active',
    totalSpent: 12000,
    registerTime: '2024-01-01',
    lastVisit: '2024-03-15',
    visitCount: 8,
    referralCount: 3
  }
])

// 等级设置数据
const levelSettings = ref([
  {
    id: '1',
    name: '普通会员',
    spendRequirement: 0,
    pointRequirement: 0,
    discount: 9.5,
    benefits: [
      '预约优先',
      '积分兑换',
      '生日特权'
    ]
  },
  {
    id: '2',
    name: '银卡会员',
    spendRequirement: 5000,
    pointRequirement: 1000,
    discount: 9.0,
    benefits: [
      '预约优先',
      '积分兑换',
      '生日特权',
      '专属客服'
    ]
  }
])

// 积分规则数据
const pointRules = ref([
  {
    id: '1',
    name: '消费积分',
    type: 'spend',
    points: 1,
    description: '每消费1元获得1积分',
    status: 'active'
  },
  {
    id: '2',
    name: '推荐奖励',
    type: 'referral',
    points: 100,
    description: '成功推荐新会员注册',
    status: 'active'
  }
])

// 积分历史数据
const pointsHistory = ref([
  {
    time: '2024-03-15 14:30',
    type: 'spend',
    points: 100,
    description: '门诊消费',
    balance: 1200
  },
  {
    time: '2024-03-10 10:20',
    type: 'referral',
    points: 100,
    description: '推荐新会员',
    balance: 1100
  }
])

// 编辑状态
const showMemberDialog = ref(false)
const showLevelDialog = ref(false)
const showPointRuleDialog = ref(false)
const showPointsDetailDialog = ref(false)
const editingMember = ref({})
const editingLevel = ref({})
const editingPointRule = ref({})
const selectedMember = ref(null)

// 状态处理函数
const getMemberLevelType = (level) => {
  const types = {
    normal: '',
    silver: 'info',
    gold: 'warning',
    diamond: 'success'
  }
  return types[level]
}
// 会员等级标签
const getMemberLevelLabel = (level) => {
  const labels = {
    normal: '普通会员',
    silver: '银卡会员',
    gold: '金卡会员',
    diamond: '钻石会员'
  }
  return labels[level]
}
// 积分规则类型
const getPointRuleType = (type) => {
  const types = {
    spend: 'success',
    referral: 'warning',
    activity: 'info'
  }
  return types[type]
}
// 积分规则标签
const getPointRuleLabel = (type) => {
  const labels = {
    spend: '消费获得',
    referral: '推荐奖励',
    activity: '活动奖励'
  }
  return labels[type]
}
// 积分历史类型
const getPointHistoryType = (type) => {
  const types = {
    spend: 'success',
    referral: 'warning',
    activity: 'info',
    exchange: 'danger'
  }
  return types[type]
}
// 积分历史标签
const getPointHistoryLabel = (type) => {
  const labels = {
    spend: '消费获得',
    referral: '推荐奖励',
    activity: '活动奖励',
    exchange: '积分兑换'
  }
  return labels[type]
}

// 搜索相关方法
const handleSearch = () => {
  ElMessage.success('搜索功能待实现')
}
// 重置搜索
const handleReset = () => {
  searchForm.value = {
    keyword: '',
    level: ''
  }
}

// 会员管理方法
const handleEditMember = (row) => {
  editingMember.value = { ...row }
  showMemberDialog.value = true
}
// 确认会员编辑
const handleConfirmMember = () => {
  ElMessage.success('会员编辑确认')
  members.value.push(editingMember.value)
  showMemberDialog.value = false
}
// 查看积分
const handleViewPoints = (row) => {
  selectedMember.value = row
  showPointsDetailDialog.value = true
}
// 确认积分明细
const handleConfirmPointsDetail = () => {
  ElMessage.success('积分明细确认')
  showPointsDetailDialog.value = false
}
// 切换会员状态
const handleToggleMemberStatus = (row) => {
  const action = row.status === 'active' ? '冻结' : '解冻'
  ElMessageBox.confirm(`确定要${action}该会员吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    row.status = row.status === 'active' ? 'frozen' : 'active'
    ElMessage.success(`会员已${action}`)
  })
}
// 新增等级
const handleCreateLevel = () => {
  editingLevel.value = {
    id: '',
    name: '',
    spendRequirement: 0,
    pointRequirement: 0,
    discount: 10,
    benefits: ['']
  }
  showLevelDialog.value = true
}
// 编辑等级
const handleEditLevel = (row) => {
  editingLevel.value = { ...row }
  showLevelDialog.value = true
}
// 等级确认
const handleConfirmLevel = () => {
  ElMessage.success('等级确认')
  levelSettings.value.push(editingLevel.value)
  showLevelDialog.value = false
}
// 删除等级
const handleDeleteLevel = (row) => {
  ElMessageBox.confirm('确定删除该等级吗？', '提示', {
    type: 'warning'
  }).then(() => {
    levelSettings.value = levelSettings.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  })
}
// 新增积分规则
const addBenefit = () => {
  editingLevel.value.benefits.push('')
}
// 删除积分规则
const removeBenefit = (index) => {
  editingLevel.value.benefits.splice(index, 1)
}

// 积分规则管理方法
const handleCreatePointRule = () => {
  editingPointRule.value = {
    id: '',
    name: '',
    type: '',
    points: 0,
    description: '',
    status: 'active'
  }
  showPointRuleDialog.value = true
}
// 编辑积分规则
const handleEditPointRule = (row) => {
  editingPointRule.value = { ...row }
  showPointRuleDialog.value = true
}
// 积分规则确认
const handleConfirmPointRule = () => {
  ElMessage.success('积分规则确认')
  pointRules.value.push(editingPointRule.value)
  showPointRuleDialog.value = false
}
// 删除积分规则
const handleDeletePointRule = (row) => {
  ElMessageBox.confirm('确定删除该规则吗？', '提示', {
    type: 'warning'
  }).then(() => {
    pointRules.value = pointRules.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  })
}
// 切换积分规则状态
const handleTogglePointRule = (row) => {
  ElMessage.success(`规则已${row.status === 'active' ? '启用' : '停用'}`)
}
</script>